package com.amkai.aes.webservice.binary.objecthandler;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;

import com.amkai.aes.aescommon.service.binary.job.ProcedureCarrierCodeJob;
import com.amkai.aes.aescommon.service.result.ProcedureCarrierCodeResult;
import com.amkai.aes.generatedbeans.dictionary.Item;
import com.amkai.aes.generatedbeans.procedure.CarrierCodes;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;

public class ProcedureCarrierCodeHandler implements JobObjectHandler<ProcedureCarrierCodeJob, java.io.Serializable, ProcedureCarrierCodeResult>{

	private static final String QUERY =
		"SELECT carrierCode FROM CarrierCodes carrierCode" +
			" WHERE carrierCode.procedure = :procedure";
	
	@Override
	@SuppressWarnings("unchecked")
	public ProcedureCarrierCodeResult process(ProcedureCarrierCodeJob job,
			Serializable object) throws Exception {
		ProcedureCarrierCodeResult result = new ProcedureCarrierCodeResult();
		
		if(job.getProcedure() != null && job.getProcedure().getId() != null){
			SessionManager manager = SiteManager.Start();
			manager.openSession();
			try{			
				Query query = manager.execute(QUERY);
				query.setParameter("procedure", job.getProcedure());
				List<CarrierCodes> carrierCodes = query.list();
				fetchCarrierCode(carrierCodes);
				
				result.setCarrierCodes(carrierCodes);
			}finally{
				manager.closeSession();
			}
		}
		else {
			result.setCarrierCodes(new ArrayList<CarrierCodes>());
		}
		
		return result;
	}
	
	private void fetchCarrierCode(List<CarrierCodes> carrierCodes){
		for(CarrierCodes carrierCode : carrierCodes){
			fetchItem(carrierCode.getCptCode());
			fetchItem(carrierCode.getCptModifier1());
			fetchItem(carrierCode.getCptModifier2());
			fetchItem(carrierCode.getCptModifier3());
			fetchItem(carrierCode.getCptModifier4());
			fetchItem(carrierCode.getRevenueCode());
			fetchItem(carrierCode.getInsuranceCarrier());
			fetchItem(carrierCode.getIcdProcedureCode1());
			fetchItem(carrierCode.getIcdProcedureCode2());
			fetchItem(carrierCode.getIcdProcedureCode3());
			fetchItem(carrierCode.getAdditionalReveneuCode());
		}
	}
	
	private void fetchItem(Item item){
		if(item != null){
			item.getName();
		}		
	}
}
